import multiprocessing
from datetime import datetime
from time import sleep

import requests
from requests.exceptions import ConnectionError

from Spider.config import CONFIG
from Spider.main import main


def client_test():
    try:
        requests.get(CONFIG.LOCAL_URL + "/api/health/")
        return True
    except ConnectionError:
        print("请先启动客户端 launch_client.bat")
        return False


def schedular():
    print("启动调度器")
    child_process = None  # 是否存在子进程

    while True:
        test_flag = client_test()
        if test_flag:
            break
        sleep(3)

    while True:
        current_time = datetime.now().time()
        running = False  # 子进程是否可运行

        if CONFIG.AM_START <= current_time <= CONFIG.AM_END or CONFIG.PM_START <= current_time <= CONFIG.PM_END:
            # 判断时候在可运行时间内
            running = True
        else:
            print("不在运行时间内，请勿关闭调度器")
        # 在时间段内则开启子进程
        if running and child_process is None:
            print("启动后台程序")
            child_process = multiprocessing.Process(target=main)
            child_process.start()
            print("后台程序启动成功")

        # 非记录时间则退出子进程
        if not running and child_process is not None:
            print("关闭后台程序")
            child_process.terminate()
            child_process.join()
            child_process = None
            print("后台程序关闭成功")
        sleep(5)


if __name__ == '__main__':
    schedular()
